/*
 * exame_17Set2011.c
 * loadbal
 *
 *  Created on: Jun 9, 2012
 *      Author: ubuntu
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv) {

	if (argc < 2) {
		fprintf(stderr, "Usage: %s [progs] \n", argv[0]);
		exit(EXIT_FAILURE);
	}

	int numeroProgs = argc - 1;

	//int * pipes[numeroProgs] =
	int ** pipes = (int **) malloc(sizeof(int *) * numeroProgs);

	int i = 0;

	for (i = 0; i < numeroProgs; i++) {

		int * fdsend = (int*) malloc(sizeof(int) * 2);
		pipe(fdsend);
		pipes[i] = fdsend;
	}

	//	printf("pipes %d\n", pipes); // mts
	//	printf("&pipes %d\n", &pipes); // mts
	//	for (i = 0; i < numeroProgs; i++) {
	//		printf("pipes[%d]%d\n", i, pipes[i]); // mts,  [+pequeno] [igual]
	//		printf("&pipes[%d]%d\n", i, &pipes[i]); // mts,  [+pequeno] [igual]
	//		printf("&pipes[%d][0]%d\n", i, &pipes[i][0]); //pequeno
	//		printf("&pipes[%d][1]%d\n", i, &pipes[i][1]); // pequeno
	//		printf("pipes[%d][0]%d\n", i, pipes[i][0]); //pequeno
	//		printf("pipes[%d][1]%d\n", i, pipes[i][1]); // pequeno
	//	}
	// return 0;

	for (i = 0; i < numeroProgs; i++) {
		pid_t pid = fork();

		if (pid == 0) {
			close(pipes[i][1]);
			dup2(pipes[i][0], STDIN_FILENO);
			execl(argv[i + 1], argv[i + 1], NULL);
			perror("Ecxec");
			exit(EXIT_FAILURE);
		} else {
			close(pipes[i][0]);
		}
	}

	for (i = 0; i <= numeroProgs; i++) {
		if (i==numeroProgs) {
			i=0;
		}
		int size = 256;
		char buffer[size];

		int nBytesreaded = read(STDIN_FILENO, buffer, size);

		write(pipes[i][1], buffer, nBytesreaded);


	}

}
